package com.asiainfo.heshanghui.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asiainfo.heshanghui.configs.ConstantsME;
import com.asiainfo.heshanghui.configs.InterfaceConfig;
import com.framework2.customview.TitleView;
import com.asiainfo.heshanghui.entity.IdsInfo;
import com.asiainfo.heshanghui.entity.ScanInfo;
import com.asiainfo.heshanghui.networkModel.HttpUtil;
import com.framework.Utils.PreferencesHelper;
import com.framework.Utils.RegularUtil;
import com.framework.Utils.RequestPermissionsUtil;
import com.framework.Utils.ScreenUtils;
import com.framework.Utils.ToastUtil;
import com.framework.Utils.Utils;
import com.framework.Utils.Y;
import com.framework2.base.BaseOnClickListener;
import com.framework2.base.BiuooBaseActivity;
import com.framework2.dialog.ExitDialog;
import com.framework2.greendao.GreenDaoManager;
import com.framework2.popupwindow.InputPopupwindow;
import com.framework2.popupwindow.SuggestPopupwindow;
import com.framework2.utils.BiuooCollectionUtil;
import com.framework2.utils.BiuooCustomProgressDialogUtils;
import com.framework2.utils.PicToastUtil;
import com.framework2.utils.ResetConstantUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.asiainfo.heshanghui.R;
import com.zxing.camera.CameraManager;
import com.zxing.decoding.CaptureActivityHandler;
import com.zxing.decoding.InactivityTimer;
import com.zxing.view.ViewfinderView;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Vector;

/**
 * 扫描页/销售
 *
 * @author Yangjie
 *         className ScanActivity
 *         created at  2017/3/16  14:44
 */
public class ScanActivity extends BiuooBaseActivity implements View.OnClickListener, SurfaceHolder.Callback {
    private TitleView titleView;
    private RelativeLayout floatLayout;
    private TextView tv_count;
    private ImageView iv_scan, iv_input;
    private TextView tv_scan, tv_input;
    private TextView tv_input_imei;
    private boolean clickRight = false;
    private boolean manuallyInput = true;//是否点击手动输入
    private String tempIMEI;
    private boolean hasCameraPermission = false;

    @SuppressWarnings("unchecked")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.setTranslucentStatus(this, true);
        Utils.setStatusBarTintDrawable(this, R.mipmap.biuoo_bg_top);
        setContentView(R.layout.activity_scan);
        initView();
        hasCameraPermission = !(RequestPermissionsUtil.getInstance().checkPermissionsThenRequest(this, new String[]{Manifest.permission.CAMERA}, RequestPermissionsUtil.PERMISSION_CAMERA));
        if (hasCameraPermission) {
            initParametersThenAutoFocus();
        }
        if (getIntent() == null || !getIntent().getBooleanExtra(ConstantsME.avoidClear, false)) {
            //删除DB已有的ScanInfo
            GreenDaoManager.getInstance().deleteAll(ScanActivity.this, ScanInfo.class);
            ResetConstantUtil.getInstance().resetOrderClientInfo();//清除订单页面用户缓存信息
        }

    }

    /**
     * 有正在编辑的数据
     *
     * @return
     */
    private boolean hasDataOnEditing() {
        List list = GreenDaoManager.getInstance().queryEntityList(ScanActivity.this, ScanInfo.class);
        return !BiuooCollectionUtil.getInstance().isEmpty(list);
    }

    private void initParametersThenAutoFocus() {
        initParameters();
        /*以下2句--自动扫描*/
        PreferencesHelper.getInstance().putInfo(ConstantsME.cameraAutoFocus, true);//自动对焦扫描
        viewfinderView.setShowRandomCircle(true);//viewfinderView显示扫描随机点
    }

    private void initView() {
        titleView = (TitleView) findViewById(R.id.titleView);
        titleView.setTitle(R.string.biuoo_goods_output).setRightClickListner(this).setRightTxt("下一步").setRightVisible(false).setLeftOnClickListener(new BaseOnClickListener() {
            @Override
            protected void onBaseClick(View v) {
                if (hasDataOnEditing()) {
                    final ExitDialog dialog =
                            new ExitDialog(ScanActivity.this);
                    dialog.setOnSureClickListener(new ExitDialog.OnSureClickListener() {
                        @Override
                        public void onSureClickListener(String info) {
                            GreenDaoManager.getInstance().deleteAll(ScanActivity.this, ScanInfo.class);
                            dialog.dismiss();
                            finishActivity();
                        }
                    }).showDialog();
                } else
                    finishActivity();
            }
        });

        floatLayout = (RelativeLayout) findViewById(R.id.floatLayout);
        tv_count = (TextView) findViewById(R.id.tv_count);
        //底部扫码，手动输入
        iv_scan = (ImageView) findViewById(R.id.iv_scan);
        iv_input = (ImageView) findViewById(R.id.iv_input);
        tv_scan = (TextView) findViewById(R.id.tv_scan);
        tv_input = (TextView) findViewById(R.id.tv_input);
        tv_input_imei = (TextView) findViewById(R.id.tv_input_imei);
        initInputTopMargin();
    }

    /**
     * 改变<手动输入>topMargin
     */
    private void initInputTopMargin() {
        if (tv_input_imei != null) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tv_input_imei.getLayoutParams();
            params.setMargins(0, (int) (ScreenUtils.getInstance().getScreenHeightPx(this) * ConstantsME.scanMarginTopFloat)
                            - ScreenUtils.getInstance().getStatusBarHeightPx(this)
                            + CameraManager.getFrameHeight()
                            + ScreenUtils.getInstance().dip2px(this, 30 + 30)
                    , 0, 0);
            tv_input_imei.setLayoutParams(params);
        }
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_input_imei:
                manuallyInput = true;
                showInputPop(null);
                break;
            case R.id.rightLayout:
                startActivity(ScanListDetailActivity.class);
                break;
            case R.id.scanLayout:
                clickRight = false;
                showManuallyInput(clickRight);
//                startScan();
                onResume();
                break;
            case R.id.inputLayout:
//                clickRight = true;
//                showManuallyInput(clickRight);
//                onPause();


                startActivity(BiuooGoodsOutputManualActivity.class);
                break;
            default:
                break;
        }
    }


    /**
     * @param isManuallyInput 是否 手动输入
     */
    private void showManuallyInput(boolean isManuallyInput) {
        this.clickRight = isManuallyInput;
        if (isManuallyInput) {
            if (null != tv_input && null != tv_scan) {
                tv_input.setTextColor(getResources().getColor(R.color._blue));
                tv_scan.setTextColor(getResources().getColor(R.color.white));
            }
            if (null != iv_input && null != iv_scan) {
                iv_input.setImageResource(R.mipmap.bg_accessories_input_2);
                iv_scan.setImageResource(R.mipmap.bg_scan_1);
            }
        } else {
            if (null != tv_input && null != tv_scan) {
                tv_input.setTextColor(getResources().getColor(R.color.white));
                tv_scan.setTextColor(getResources().getColor(R.color._blue));
            }
            if (null != iv_input && null != iv_scan) {
                iv_input.setImageResource(R.mipmap.bg_accessories_input_1);
                iv_scan.setImageResource(R.mipmap.bg_scan_2);
            }
        }
    }

    /**
     * 显示/隐藏右边
     */
    private void showRightTxt(boolean rightVisible) {
        if (titleView != null)
            titleView.setRightVisible(rightVisible);
    }

    /**
     * @param count 已录入数量
     */
    private void updateTopBar(int count) {
        if (count > 0) {
            floatLayout.setVisibility(View.VISIBLE);
            SpannableString spannableString = new SpannableString("已选择" + count + "件商品");
            spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color._blue)), 3, spannableString.length() - 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv_count.setText(spannableString);
            showRightTxt(true);
        } else {
            floatLayout.setVisibility(View.GONE);
            tv_count.setText("已选择" + 0 + "件商品");
            showRightTxt(false);
        }
    }

    private boolean checkHasIMEI(@NonNull String imei) {
        List list = GreenDaoManager.getInstance().queryEntityList(ScanActivity.this, ScanInfo.class);
        Y.y("checkHasIMEI:list:" + (list == null));
        if (list != null) {
            Y.y("checkHasIMEI:list:" + list.size());
        }
        if (!BiuooCollectionUtil.getInstance().isEmpty(list)) {
            int size = list.size();
            for (int i = 0; i < size; i++) {
                ScanInfo info = (ScanInfo) list.get(i);
                Y.y("checkHasIMEI:" + info.getImei());
                if (null != info && TextUtils.equals(info.getImei(), imei)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * @param scanInfo scanInfo
     */
    @SuppressWarnings("unchecked")
    private void insertOrUpdateDB_then_updateTopBar(final ScanInfo scanInfo) {
        if (null == scanInfo)
            return;
        List list = GreenDaoManager.getInstance().queryEntityList(ScanActivity.this, ScanInfo.class);
        if (BiuooCollectionUtil.getInstance().isEmpty(list)) {
            boolean a = GreenDaoManager.getInstance().insertEntity(ScanActivity.this, scanInfo);
            Y.y("插入数据库:" + a);
            Utils.h.post(new Runnable() {
                @Override
                public void run() {
                    updateTopBar(1);
                }
            });
        } else {
            int size = list.size();
            for (int i = 0; i < size; i++) {
                ScanInfo info = (ScanInfo) list.get(i);
                if (null != info && TextUtils.equals(info.getImei(), scanInfo.getImei())) {
                    info.setPrice(scanInfo.getPrice());
                    GreenDaoManager.getInstance().updateEntity(ScanActivity.this, info);
                    return;
                }
            }
            boolean ins = GreenDaoManager.getInstance().insertEntity(ScanActivity.this, scanInfo);
            List list2 = GreenDaoManager.getInstance().queryEntityList(ScanActivity.this, ScanInfo.class);
//            if (!CollectionUtil.getInstance().isEmpty(list2)){
//                for ()
//            }
            final int lenth = list2.size();
            Utils.h.post(new Runnable() {
                @Override
                public void run() {
                    updateTopBar(lenth);
                }
            });
        }
    }

    @SuppressWarnings("unchecked")
    private void updateDB() {
        List list = GreenDaoManager.getInstance().queryEntityList(ScanActivity.this, ScanInfo.class);
        int count = 0;
        int len = list.size();
        for (int i = 0; i < len; i++) {
            if (null != list.get(i)) {
                ScanInfo info = (ScanInfo) list.get(i);
                if (null != info) {
                    count += info.getCount();
                }
            }
        }
        updateTopBar(BiuooCollectionUtil.getInstance().isEmpty(list) ? 0 : count);
    }

    /**
     * 点击检查ime
     *
     * @param pop
     * @param info
     */
    private void onClickCheckImei(InputPopupwindow pop, String info) {
        if (RegularUtil.getInstance().isNumberAtLeast15bit(info.trim())) {
            pop.dismiss();
            BiuooCustomProgressDialogUtils.showProcessDialog(ScanActivity.this, "正在查询");
            Utils.isCloseSoftInputMethod(ScanActivity.this, pop.getEditText(), true);
            tempIMEI = info;
            if (TextUtils.isEmpty(PreferencesHelper.getInstance().getStringData(ConstantsME.currentShopId))) {
                requestJustShopIds(info);
            } else {
                requestQueryQRcode(info, PreferencesHelper.getInstance().getStringData(ConstantsME.currentShopId));
            }
        } else {
            PicToastUtil.showPicToast(ScanActivity.this, "IMEI必须为15位数字");
        }
    }

    private String beforeTextChanged;

    /**
     * 显示输入pop，ScanInfo为空时，输入；不为空时，是显示imei查询成功pop
     *
     * @param scanInfo scanInfo
     */
    private void showInputPop(final ScanInfo scanInfo) {
        onPause();//暂停相机
        final InputPopupwindow pop = new InputPopupwindow(this);
        if (scanInfo != null) {
            pop.setTitle(scanInfo.getName());
            pop.setContentVisible(false);
            pop.setContent("建议售价:" + (scanInfo.getPrice() > 0 ? scanInfo.getPrice() : "暂无"));
            pop.setSureButtonText("确定");
            DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance();
            decimalFormat.applyPattern("0.00");
            pop.setEditTextHint("请输入销售价格" + "，建议售价:" + (scanInfo.getPrice() > 0 ? decimalFormat.format(scanInfo.getPrice()) + "元" : "暂无"));
            pop.setShowClearButton(false);
            pop.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        } else {
            pop.setContentVisible(false);
            pop.setSureButtonText("下一步");
            pop.setEditTextHint("请输入IMEI号");
            pop.setShowClearButton(true);
            pop.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
            if (!TextUtils.isEmpty(tempIMEI)) {
                pop.getEditText().setText(tempIMEI);
                pop.getEditText().setSelection(tempIMEI.length());
                pop.showClearButton();
//                pop.getEditText().setSelectAllOnFocus(true);
//                pop.getEditText().selectAll();
            }
        }
        pop.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (!TextUtils.isEmpty(s) && s.toString().length() <= 10) {
                    beforeTextChanged = s.toString();
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (scanInfo == null && RegularUtil.getInstance().isNumberAtLeast15bit(s.toString())) {
                    if (checkHasIMEI(s.toString())) {
                        pop.dismiss();
                        //重复IMEI
                        showDuplicatePopupWindow(s.toString());
                    } else
                        onClickCheckImei(pop, s.toString());
                } else if (scanInfo != null && !TextUtils.isEmpty(s) && s.toString().length() > 10) {
//                    pop.getEditText().setText(s.subSequence(0, s.length() - 1));
//                    pop.getEditText().setSelection(s.length() - 1);
                    pop.getEditText().setText(beforeTextChanged);
                    pop.getEditText().setSelection(beforeTextChanged.length());
                    PicToastUtil.showPicToast(ScanActivity.this, "请不要超过十位");
                } else if (scanInfo != null && RegularUtil.getInstance().isAtleast3bitNumberAfterDigit(s.toString())) {
                    String temp = pop.getEditText().getText().toString();
                    pop.getEditText().setText(temp.substring(0, temp.length() - 1));
                    pop.getEditText().setSelection(pop.getEditText().getText().toString().length());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        pop.setOnSureClickListener(new InputPopupwindow.OnSureClickListener() {
            @Override
            public void onSureClickListener(String info) {
                if (scanInfo == null) {
                    if (checkHasIMEI(info)) {
                        pop.dismiss();
                        //重复IMEI
                        showDuplicatePopupWindow(info);
                    } else
                        onClickCheckImei(pop, info);
                } else {
                    try {
                        Double.parseDouble(info);
                        Utils.isCloseSoftInputMethod(ScanActivity.this, pop.getEditText(), true);
                        scanInfo.setPrice(Double.parseDouble(info));
                        insertOrUpdateDB_then_updateTopBar(scanInfo);
                        tempIMEI = "";
                        pop.dismiss();
                        onResume();
//                        startActivity(AccessoriesActivity.class, scanInfo);
                    } catch (Exception e) {
                        e.printStackTrace();
                        PicToastUtil.showPicToast(ScanActivity.this, "请输入售价");
                    }
                }
            }
        });
        pop.setOnCancelClickListener(new InputPopupwindow.OnCancelClickListener() {
            @Override
            public void onCancelClickListener() {
                pop.dismiss();
                onResume();
            }
        });
        try {
            pop.showAsDropDown(titleView.getRightLayout());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showDuplicatePopupWindow(final String imei) {
        tempIMEI = imei;
        onPause();//暂停相机
        final SuggestPopupwindow pop = new SuggestPopupwindow(this);
        pop.setTitle("重复IMEI，是否忽略之前IMEI?");
        pop.setContent("顶部栏已包含该IMEI号");
        pop.setSureButtonText("忽略");
        pop.setCancelButtonText("取消");
        pop.setOnSureClickListener(new SuggestPopupwindow.OnSureClickListener() {
            @Override
            public void onSureClickListener(String info) {
                pop.dismiss();
                BiuooCustomProgressDialogUtils.showProcessDialog(ScanActivity.this, "正在查询");
                if (TextUtils.isEmpty(PreferencesHelper.getInstance().getStringData(ConstantsME.currentShopId))) {
                    requestJustShopIds(imei);
                } else {
                    requestQueryQRcode(imei, PreferencesHelper.getInstance().getStringData(ConstantsME.currentShopId));
                }
            }
        }).setOnCancelClickListener(new SuggestPopupwindow.OnCancelClickListener() {
            @Override
            public void onCancelClickListener() {
                pop.dismiss();
                showInputPop(null);
//                onResume();
            }
        });
        try {
            pop.showAsDropDown(titleView.getRightLayout());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showSuggestPopupWindow() {
        onPause();//暂停相机
        final SuggestPopupwindow pop = new SuggestPopupwindow(this);
        if (manuallyInput) {
            pop.setSureButtonText("重新输入");
        } else {
            tempIMEI = "";
            pop.setSureButtonText("手动输入");
        }
        pop.setOnSureClickListener(new SuggestPopupwindow.OnSureClickListener() {
            @Override
            public void onSureClickListener(String info) {
                pop.dismiss();
                showInputPop(null);
            }
        });
        pop.setOnCancelClickListener(new SuggestPopupwindow.OnCancelClickListener() {
            @Override
            public void onCancelClickListener() {
                pop.dismiss();
                onResume();
            }
        });
        try {
            pop.showAsDropDown(titleView.getRightLayout());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 请求查询二维码code
     */
    private void requestQueryQRcode(String code, String shopId) {
        if (TextUtils.isEmpty(code))
            return;
        tempIMEI = code;
        HttpUtil.getInstance().requestQueryQRcode(this, InterfaceConfig.queryCode, shopId, code, new HttpUtil.OnRequestResult<ScanInfo>() {
            @Override
            public void onSuccess(ScanInfo... scanInfo) {
                BiuooCustomProgressDialogUtils.dismissProcessDialog();
                if (null != scanInfo) {
                    scanInfo[0].setCount(1);
                    showInputPop(scanInfo[0]);
                } else {
                    showSuggestPopupWindow();
                }
            }

            @Override
            public void onFail(int code, String msg) {
                BiuooCustomProgressDialogUtils.dismissProcessDialog();
                if (code == 1) {
                    showSuggestPopupWindow();
                } else {
                    ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "查询IMEI失败" : msg);
                }
            }
        });
    }

    private void requestJustShopIds(final String code) {
        HttpUtil.getInstance().requestJustShopIds(ScanActivity.this, InterfaceConfig.shopIds, new HttpUtil.OnRequestListResult<IdsInfo>() {
            @Override
            public void onSuccess(List<IdsInfo> list, String... msg) {
                if (!BiuooCollectionUtil.getInstance().isEmpty(list)) {
                    PreferencesHelper.getInstance().putInfo(ConstantsME.currentShopId, list.get(0).getShopId());
                    PreferencesHelper.getInstance().putInfo(ConstantsME.companyId, list.get(0).getCompanyId());
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < list.size(); i++) {
                        if (i == 0) {
                            stringBuilder.append(list.get(i).getShopId());
                        } else {
                            stringBuilder.append(",").append(list.get(i).getShopId());
                        }
                    }
                    PreferencesHelper.getInstance().putInfo(ConstantsME.shopIds, stringBuilder.toString());
                    requestQueryQRcode(code, list.get(0).getShopId());
                }
            }

            @Override
            public void onFail(int code, String msg) {
                ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "未获取店铺Id" : msg);
                BiuooCustomProgressDialogUtils.dismissProcessDialog();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            Utils.isCloseSoftInputMethod(this, null, true);
            if (hasDataOnEditing()) {
                final ExitDialog dialog =
                        new ExitDialog(this);
                dialog.setOnSureClickListener(new ExitDialog.OnSureClickListener() {
                    @Override
                    public void onSureClickListener(String info) {
                        GreenDaoManager.getInstance().deleteAll(ScanActivity.this, ScanInfo.class);
                        dialog.dismiss();
                        finishActivity();
                    }
                }).showDialog();
            } else
                finishActivity();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == RequestPermissionsUtil.PERMISSION_CAMERA) {
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                initParametersThenAutoFocus();
                if (null != viewfinderView)
                    viewfinderView.setShowRandomCircle(true);
                SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preSurfaceView);
                SurfaceHolder surfaceHolder = surfaceView.getHolder();
                initCamera(surfaceHolder);
            } else {
                ToastUtil.getInstance().showToast("相机权限未开启，请手动开启");
                RequestPermissionsUtil.getInstance().showInstalledAppDetailSettingIntent(this, getPackageName());
            }
        }
    }

    /*以下QR扫描相关************************************************************************************************************************************/
    //扫描相关参数*********************************//
    private CaptureActivityHandler captureActivityHandler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    //扫描相关参数*********************************//

    /**
     * 扫描相关
     */
    private void initParameters() {
        CameraManager.init(getApplication());
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinderView);
        viewfinderView.setCornerLenth(ScreenUtils.getInstance().dip2px(this, 17));
        viewfinderView.setCornerThickness(ScreenUtils.getInstance().dip2px(this, 3));
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
//        CameraManager.setMaxFrameWidth(ScreenUtils.getInstance().getScreenWidthPx(this) - 2 * ScreenUtils.getInstance().dip2px(this, 50));//设置取景框最大宽度
//        CameraManager.setMaxFrameHeight(ScreenUtils.getInstance().dip2px(this, 40));//设置取景框最大高度
//        CameraManager.setViewfinderScreenWidth(CameraManager.getMaxFrameWidth());
//        CameraManager.setViewfinderScreenHeight(CameraManager.getMaxFrameHeight());

        int topOffset = (int) (ScreenUtils.getInstance().getScreenHeightPx(this) * ConstantsME.scanMarginTopFloat);
        int leftOffset = ScreenUtils.getInstance().dip2px(this, 40);
        int width = ScreenUtils.getInstance().getScreenWidthPx(this) - 2 * ScreenUtils.getInstance().dip2px(this, 50);//设置取景框最大宽度
        int height = width / 3;
        Rect framingRect = new Rect(leftOffset, topOffset, ScreenUtils.getInstance().getScreenWidthPx(this) - leftOffset,
                topOffset + height);
        CameraManager.setDecodeMultiple(false);
        CameraManager.get().setRectInPreview(framingRect);
        CameraManager.setFrameWidth(width);
        CameraManager.setFrameHeight(height);
        viewfinderView.postInvalidate();

        initInputTopMargin();//改变<手动输入>topMargin
    }

    /**
     * 开始/重新 扫描并解码
     */
    private void startScan() {
        if (null != captureActivityHandler) {
            captureActivityHandler.startScan();
            viewfinderView.setShowRandomCircle(true);
        } else {
            onResume();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null != viewfinderView)
            viewfinderView.setShowRandomCircle(true);
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preSurfaceView);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (!hasCameraPermission) {
            initParametersThenAutoFocus();
        }
        if (hasSurface) {
            if (!hasCameraPermission) {//// TODO: 2017/4/24 我添加的
                initParametersThenAutoFocus();
            }
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
//        decodeFormats = null;
//        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
        //*********************************以上为二维码
        showManuallyInput(clickRight);
        updateDB();
    }

    @Override
    protected void onPause() {
        super.onPause();
        viewfinderView.setShowRandomCircle(false);
        if (captureActivityHandler != null) {
            captureActivityHandler.quitSynchronously();
            captureActivityHandler = null;
        }
        if (null != CameraManager.get())
            CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        if (null != inactivityTimer) {
            inactivityTimer.shutdown();
        }
        super.onDestroy();
    }

    /**
     * 处理扫描结果
     *
     * @param results       result
     * @param barcodeBitmap barcode
     */
    public void handleDecode(Result[] results, Bitmap barcodeBitmap) {
        if (captureActivityHandler != null) {
            captureActivityHandler.quitSynchronously();
            captureActivityHandler = null;
        }
        if (results != null && results[0] != null) {
            ToastUtil.getInstance().showToast("" + results[0].getText());
            CameraManager.get().closeDriver();
            inactivityTimer.onActivity();
            playBeepSoundAndVibrate();
            tv_scan.setText("点我继续");
            showManuallyInput(clickRight);
            if (!TextUtils.isEmpty(results[0].getText())) {
                manuallyInput = false;
                if (checkHasIMEI(results[0].getText())) {
                    //重复IMEI
                    showDuplicatePopupWindow(results[0].getText());
                } else {
                    BiuooCustomProgressDialogUtils.showProcessDialog(ScanActivity.this, "正在查询");
                    if (TextUtils.isEmpty(PreferencesHelper.getInstance().getStringData(ConstantsME.currentShopId))) {
                        requestJustShopIds(results[0].getText());
                    } else {
                        requestQueryQRcode(results[0].getText(), PreferencesHelper.getInstance().getStringData(ConstantsME.currentShopId));
                    }
                }
            }
        }
    }

    private boolean initCamera(SurfaceHolder surfaceHolder) {
        try {
            Y.y("initCamera:" + 1);
            CameraManager.get().openDriver(surfaceHolder, viewfinderView);
        } catch (IOException ioe) {
            Y.y("initCamera_IOException:" + ioe.getMessage());
            return false;
        } catch (RuntimeException e) {
            Y.y("initCamera_RuntimeException:" + e.getMessage());
            return false;
        }
//        if (decodeFormats == null || decodeFormats.isEmpty()) {
//            decodeFormats = new Vector<BarcodeFormat>();
//            decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);//只解析条形码
//        }

        if (captureActivityHandler == null) {
            captureActivityHandler = new CaptureActivityHandler(this, decodeFormats, characterSet, true);
        }
        return true;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getCaptureActivityHandler() {
        return captureActivityHandler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };
    /*以上QR扫描相关************************************************************************************************************************************/
}
